package anti5mao;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;

public class CallbackServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) {
		Twitter twitter = Anti5maoServlet.getClient();
		RequestToken requestToken = getRequestToken(request.getCookies());
		if (requestToken == null) {
			try {
				response.getWriter().println("error!");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			String verifier = request.getParameter("oauth_verifier");
			try {
				AccessToken accessToken = twitter.getOAuthAccessToken(
						requestToken, verifier);
				User user = twitter.verifyCredentials();
				if(user!=null){
					Setting.insert(user.getScreenName(), accessToken.getToken(), accessToken.getTokenSecret());
				}
				
				response.addCookie(new Cookie("acs_t", accessToken.getToken()));
				response.getWriter().println("done!");
			} catch (TwitterException e) {
				
			} catch (IOException e) {
				try {
					response.getWriter().println("error!");
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}

	}
	

	private RequestToken getRequestToken(Cookie[] cookies) {
		int len = cookies.length;
		String token = null,token_secret = null;
		for (int i = 0; i < len; i++) {
			if(cookies[i].getName().equals("req_t")){
				token = cookies[i].getValue();
				continue;
			}
			if(cookies[i].getName().equals("req_t_s")){
				token_secret = cookies[i].getValue();
				continue;
			}
		}
		if(token!=null&&token_secret!=null){
			return new RequestToken(token, token_secret);
		}
		return null;
	}

}
